﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Windows.Forms;

using pokerServer.GameManagment.GameTools;

namespace ConnectionControl
{
	public class Server
	{
		private Thread t;
		private TcpListener tcpl;
		private TcpClient tcpc;
		private IPAddress add;
		private Boolean flag = true;
		private ConnectionManag cm;
		private TextBox tb;
		private ManualResetEvent mre;

		public Server(IPAddress add,TextBox tb,TextBox ucount,TextBox conCount,ListBox ulist)
		{
			this.tb = tb;
			this.add = add;
			cm = new ConnectionManag(ucount,conCount,ulist);		
			mre = new ManualResetEvent(false);
			
		}

		public void start()
		{
			//Wind32.AllocConsole(); 
			cm.reActivate();
			tcpl = new TcpListener(add, 9999);
			this.tcpl.Start();
			this.flag = true;			
			t = new Thread(new ThreadStart(run));

			t.IsBackground = true;
			t.Start();
			tb.Text = "Server Running";
		}

		public void run()
		{
			
				while (this.flag)
				{
					try 
					{
						if (!tcpl.Pending())
						{
							Thread.Sleep(100);
							continue;
						}
						this.tcpc = tcpl.AcceptTcpClient();
						this.cm.tempAdd(tcpc);
					}
					catch (SocketException es)
					{
						Console.WriteLine("Problem in TCPL:"+es.Message);
					}
					
				}
				mre.Set();
				Console.WriteLine("Server Ended");
				
			
		}

		public Boolean shutDown()
		{
			try
			{
				this.flag = false;
				Boolean ans = mre.WaitOne(1000);
				cm.shutDown();
				tb.Text = "Server Shutted Down!";
				tcpl.Stop();				
				return ans;
			}
			catch (Exception e)
			{
				tb.Text=(e.Message);
				return false;
			}
		}

	}
}
